﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Relationship 的摘要说明
/// </summary>
public class Relationship
{
	public Relationship()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
    }

    public static bool ExistRelationship(int g1, string r, int g2)
    {
        string sql = "select count(*) as n from Relationship where GuidOne=" + g1.ToString() + " and Relationship='" + r.Replace("'", "''") + "' and GuidTwo=" + g2.ToString();
        int n = Convert.ToInt32(Fun.GetField(sql, "n"));
        return n > 0;
    }

    public static void AddRelationship(int g1, string r, int g2)
    {
        if (Relationship.ExistRelationship(g1, r, g2))
        {
            return;
        }
        int g = Fun.Guid();
        string sql = "insert into Relationship(Guid,GuidOne,Relationship,GuidTwo) values(" + g.ToString() + "," + g1.ToString() + ",'" + r.Replace("'", "''") + "'," + g2.ToString() + ")";
        Fun.Execute(sql);
        //return g;
    }

    public static void DeleteRelationship(int g1, string r, int g2)
    {
        string sql = "delete from Relationship where GuidOne=" + g1.ToString() + " and Relationship='" + r.Replace("'", "''") + "' and GuidTwo=" + g2.ToString();
        Fun.Execute(sql);
    }

    public static DataTable GetGuidsByRelationship(int g, string r, bool reverse, bool asc)
    {
        string sql = "select " + (reverse ? "GuidOne" : "GuidTwo") + " from Relationship where Relationship='" + r.Replace("'", "''") + "' and " + (reverse ? "GuidTwo" : "GuidOne") + "=" + g.ToString() + " order by Guid " + (asc ? "asc" : "desc");
        return Fun.CreateDt(sql);
    }

    public static DataTable GetGuidsByRelationship(int g, string r)
    {
        return Relationship.GetGuidsByRelationship(g, r, false, false);
    }

    public static void DeleteRelationship(int RelationshipGuid)
    {
        string sql = "delete from Relationship where Guid="+RelationshipGuid.ToString();
        Fun.Execute(sql);
    }

    public static void Delete(int ObjectGuid)
    {
        string sql = "delete from Relationship where GuidOne="+ObjectGuid.ToString()+" or GuidTwo="+ObjectGuid.ToString();
        Fun.Execute(sql);
    }

    public static void Update(int g1, string r, int g2,string rr)
    {
        string sql = "update Relationship set Relationship='" + rr.Replace("'", "''") + "' where GuidOne=" + g1.ToString() + " and GuidTwo=" + g2.ToString() + " and Relationship='" + r.Replace("'", "''") + "'";
        Fun.Execute(sql);
    }
}
